package com.xianggu.Collection.queue;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author chengjy
 * @date 2025/3/24
 */
public class XiangGuQueue<Item> implements Iterable<Item>{


    private Node first;
    private Node last;
    private int size;

    private class Node{
        Item item;
        Node next;

        public Node(Item item) {
            this.item = item;
        }
    }

    // 入队
    public void enqueue(Item item){
        Node oldLast = last;
        last = new Node(item);
        // 判断原来是否有尾结点
        if(oldLast != null){
            oldLast.next = last;
        }else{
            first = last;
        }
        size++;
    }
    // 出队
    public Item dequeue(){
        Node oldFirst = first;
        if(oldFirst != null){
            first = oldFirst.next;
            size--;
            return oldFirst.item;
        }else{
            throw new NoSuchElementException("当前队列没有元素！");
        }
    }

    public boolean isEmpty(){
        return size == 0;
    }
    @Override
    public Iterator<Item> iterator() {
        return new XiangGuQueueIterator();
    }

    class XiangGuQueueIterator implements Iterator<Item>{

        Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Node old = current;
            current = old.next;
            return old.item;
        }
    }
}
